package com.lanou.sfu.songforu.adapter;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;

import android.content.Intent;
import android.net.Uri;
import android.os.Handler;

import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.URLUtil;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.sfu.songforu.R;
import com.lanou.sfu.songforu.datas.SongInfors;
import com.lanou.sfu.songforu.db.DaoSingleton;
import com.lanou.sfu.songforu.db.SongListEntity;
import com.lanou.sfu.songforu.db.SongListEntityDao;


import com.lanou.sfu.songforu.download.FileUtils;

import com.lanou.sfu.songforu.singleton.VolleySingleton;

import java.io.File;
import java.util.List;

import de.greenrobot.dao.query.QueryBuilder;
import it.sephiroth.android.library.picasso.Picasso;


/**
 * Created by dllo on 15/10/22.
 */
public class RankClassAdapter extends BaseAdapter {
    private List<SongListEntity> datas;
    private Context mContext;
    private DaoSingleton daoSingleton;
    private OnClickToShareLinstener onClickToShareLinstener;
    private StringRequest request;
    private VolleySingleton requestQueue;
    private List<SongInfors.SongurlEntity.ShowLink> urlList;


    private static Button download;

    private String songsName;

    private static final String TAG = "DOWNLOADAPK";
    private String fileEx = "";
    private String fileNa = "";
    private NotificationManager mNotificationManager;
    private Notification mNotification;
    private static final int mNotificationID = 1;// 通知的id
    private RemoteViews mRemoteViews;


    public RankClassAdapter(Context context, List<SongListEntity> lists) {
        daoSingleton = DaoSingleton.getInstance();
        datas = lists;
        mContext = context;
        requestQueue = VolleySingleton.getInstance(mContext);
    }

    public void setOnClickToShareLinstener(OnClickToShareLinstener onClickToShareLinstener) {
        this.onClickToShareLinstener = onClickToShareLinstener;
    }

    public interface OnClickToShareLinstener {
        void onClickToShare(SongListEntity songListEntity, int position);
    }


    public void addDatas(List<SongListEntity> lists) {
        datas = lists;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (datas != null && datas.size() > 0) {
            return datas.size();
        } else {
            return 0;
        }
    }

    @Override
    public SongListEntity getItem(int position) {
        if (datas != null && datas.size() > 0)
            return datas.get(position);
        else
            return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;

        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.activity_rank_class_listview_item, null);
            holder = new ViewHolder();
            holder.imageView = (ImageView) convertView.findViewById(R.id.rankClass_item_imageView);
            holder.imageButton = (ImageButton) convertView.findViewById(R.id.rank_class_item_more_imageButton);
            holder.songName = (TextView) convertView.findViewById(R.id.rank_class_song_textView);
            holder.artist = (TextView) convertView.findViewById(R.id.rank_class_artist_textView);
            holder.updata = (TextView) convertView.findViewById(R.id.rank_class_updata);
            holder.download = (Button) convertView.findViewById(R.id.my_dialog_download);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();

        }


        final SongListEntity rankClassEntity = getItem(position);
        if (rankClassEntity != null) {

            try {
                Picasso.with(mContext).load(rankClassEntity.getPic_big()).placeholder(R.mipmap.default_title_pic).into(holder.imageView);
            } catch (Exception e) {
                e.printStackTrace();
            }

            holder.artist.setText(rankClassEntity.getArtist_name());
            holder.songName.setText(rankClassEntity.getTitle());
        }

        holder.imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog myDialog = new AlertDialog.Builder(mContext).create();
                myDialog.show();
                Window window = myDialog.getWindow();
                window.setContentView(R.layout.my_dialog);

                final CheckBox love = (CheckBox) window.findViewById(R.id.my_dialog_love);
                // 判断收藏灯是否开启
                List<SongListEntity> findList = null;
                QueryBuilder<SongListEntity> queryBuilder = daoSingleton.getSongListEntityDao().queryBuilder();
                if (rankClassEntity.getSong_id() != null) {
                    findList = queryBuilder.where(SongListEntityDao.Properties.Song_id.eq(rankClassEntity.getSong_id())).list();
                }
                if (findList.size() > 0) {
                    love.setChecked(true);
                } else {
                    love.setChecked(false);
                }

                // 收藏的监听
                love.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (love.isChecked() == true) {
                            daoSingleton.getSongListEntityDao().insert(rankClassEntity);
                        } else {
                            daoSingleton.getSongListEntityDao().delete(rankClassEntity);
                        }
                    }
                });

                // 分享的监听
                Button share = (Button) window.findViewById(R.id.my_dialog_share);
                share.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onClickToShareLinstener != null) {
                            onClickToShareLinstener.onClickToShare(datas.get(position), position);
                        }
                        myDialog.dismiss();
                    }
                });

                download = (Button) window.findViewById(R.id.my_dialog_download);
                download.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String id = datas.get(position).getSong_id();
                        String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getInfos&format=json&songid=" +
                                id + "&ts=1445399459391&e=SmJtjLwgnuWRzBbIIHeXgNusY1L" +
                                "%2FXZoWyOitaQ3ExdPXWpSPZ0Fras1q%2FLVxivZr&nw=2&fr=sns&ucf=1&res=1&l2p=2943&lpb=&usup=1&lebo=0";
                        request = new StringRequest(url, new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                Gson gson = new Gson();
                                SongInfors songInfors = gson.fromJson(response, SongInfors.class);
                                urlList = songInfors.getSongurl().getUrl();
                                String currentUrl = urlList.get(position).getShow_link();
//                                Intent intent = new Intent(mContext,DownloadActivity.class);
//                                intent.putExtra("strUrl", currentUrl);
//                                mContext.startActivity(intent);

                                if (!URLUtil.isNetworkUrl(currentUrl)) {

                                    Toast.makeText(mContext, "错误的URL", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                               /* 文件会下载至local端 */
                                Toast.makeText(mContext, "下载中,请稍后...", Toast.LENGTH_SHORT).show();
                                download.setEnabled(false);
                                 /* 取得欲安装程序之文件名称 */
                                fileEx = currentUrl.substring(currentUrl.lastIndexOf(".") + 1,
                                        currentUrl.length());
                                fileNa = currentUrl.substring(currentUrl.lastIndexOf("/") + 1,
                                        currentUrl.lastIndexOf("."));
                                Log.i(TAG, "fileNa:" + fileNa);
                                getFile(currentUrl);
                                initNotification();


                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        });
                        requestQueue.addQueue(request);
                    }
                });

                Button cancel = (Button) window.findViewById(R.id.my_dialog_cancel);
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog.dismiss();
                    }
                });
                window.setLayout(700, 500);
            }
        });
        return convertView;
    }

    private class ViewHolder {
        public ImageView imageView;
        public ImageButton imageButton;
        public TextView songName, artist, updata;
        public Button download;
    }

    private void initNotification() {
        mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotification = new Notification();
        mNotification.icon = R.mipmap.d_icon;// 设置通知消息的图标
        mNotification.tickerText = "正在下载。。。";// 设置通知消息的标题
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;

        mRemoteViews = new RemoteViews(mContext.getPackageName(),
                R.layout.down_notification);

//        PendingIntent pi = PendingIntent.getActivity(context, 0, Intent.getIntent(), 0);
//        mNotification.contentIntent = pi;
    }

    /* 处理下载URL文件自定义函数 */
    private void getFile(final String strPath) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    getSourceData(strPath);
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            }
        }).start();
    }

    private FileUtils mFileUtils;

    /* 取得远程文件 */
    private void getSourceData(String strPath) throws Exception {

        mFileUtils = new FileUtils();
        mFileUtils.setDownloadCallBack(mDownloadCallBack);
        File myTempFile = mFileUtils.getData(strPath, "TestDownload", fileNa
                + "." + fileEx);

        /* 打开文件进行安装 */
        openFile(myTempFile);

    }

    /* 在手机上打开文件的method */
    private void openFile(File f) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);

        /* 调用getMIMEType()来取得MimeType */
        String type = getMIMEType(f);
        /* 设置intent的file与MimeType */
        intent.setDataAndType(Uri.fromFile(f), type);
        mContext.startActivity(intent);
        clearNotification();
    }

    /* 判断文件MimeType的method */
    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        /* 取得扩展名 */
        String end = fName
                .substring(fName.lastIndexOf(".") + 1, fName.length())
                .toLowerCase();

        /* 依扩展名的类型决定MimeType */
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio/*";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video/*";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
                || end.equals("jpeg") || end.equals("bmp")) {
            type = "image/*";
        } else if (end.equals("apk")) {
            /* android.permission.INSTALL_PACKAGES */
            type = "application/vnd.android.package-archive";
        } else {
            type = "*/*";
        }

        return type;
    }

    private Handler mHandler = new Handler();
    private Runnable mProgressTask = new Runnable() {

        @Override
        public void run() {
            long readed = mFileUtils.getReaded();
            long all = mFileUtils.getAllSize();
            StringBuffer sb = new StringBuffer("下载中...");
            sb.append(readed);
            sb.append("kb");
            sb.append("/");
            sb.append(all);
            sb.append("kb");


            if (readed < all) {
                mRemoteViews.setTextViewText(R.id.app_name, songsName);
                mRemoteViews.setTextViewText(R.id.progressTv, sb.toString());
                int size = (int) (readed * 100 / all);
                mRemoteViews.setProgressBar(R.id.progressBar, 100, size, false);
                mNotification.contentView = mRemoteViews;
                mNotificationManager.notify(mNotificationID, mNotification);
                mHandler.postDelayed(mProgressTask, 500);
            } else {
                mRemoteViews.setTextViewText(R.id.app_name, songsName);
                mRemoteViews.setTextViewText(R.id.progressTv, "下载完成");
                mRemoteViews.setProgressBar(R.id.progressBar, 100, 100, false);
                mNotification.contentView = mRemoteViews;
                mNotificationManager.notify(mNotificationID, mNotification);
                Toast.makeText(mContext, "下载完成", Toast.LENGTH_SHORT).show();
                clearNotification();
                download.setEnabled(true);


            }
        }
    };

    private FileUtils.DownloadCallBack mDownloadCallBack = new FileUtils.DownloadCallBack() {

        @Override
        public void onStart() {
            mHandler.postDelayed(mProgressTask, 500);

        }

        @Override
        public void onCompleted() {


        }
    };

    //删除通知
    private void clearNotification() {
        // 启动后删除之前我们定义的通知
        NotificationManager notificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(1);

    }
}
